#the following import is unmodified from the web2py appliances website
from applications.home.modules.facebook import Facebook

#some abstraction of the secret key for google code -- :)
#this may be open source, but you still can't have my secret key!
from applications.home.private import app_info 
#app_info.py contains
#
#def get_public_key():    return 'supercoolpublickey1234'
#def get_app_name():      return 'myapp'
#def get_callback_path(): return 'http://mycanvasurl.com'
#def get_secret_key():    return 'ultraprivatekeydontpeek'
#

class FacebookConnect:
 
    api_key = app_info.p('public_key',debug)
    app_name = app_info.p('app_name',debug)
    callback_path = app_info.p('callback_path',debug)
    request = None
    internal = True

    def __init__(self,request): 
        self.request = request
        self.request.facebook =     Facebook(
                                        api_key=self.api_key,
                                        app_name=self.app_name,
                                        callback_path=self.callback_path,
                                        secret_key=app_info.p('secret_key',debug),
                                        internal=self.internal,
                                    )

            
    def get_require_facebook_login_url(self):
        """
        Used for redirecting the user to the Facebook
        login page if not already logged in.
    
        Usage:
          require_facebook_login(request,settings)
        """
        url = None

        if not self.request.facebook.check_session(self.request):
            url = self.request.facebook.get_login_url()
            
        return url
    
    def get_facebook_user(self):
        """
        Return the fb.models.User model instance associated with
        the @facebook parameter.
    
        Usage:
          user = get_facebook_user(some_facebook_instance)
        """
        result = None
        try:
            uid=self.request.facebook.uid
            query = "SELECT uid, first_name, last_name FROM user WHERE uid=%s" % uid
            results = self.request.facebook.fql.query(query)[0]
            result = "%s %s" % (results[u'first_name'], results[u'last_name'])
        except:
            pass
        return result

facebook = FacebookConnect(request)
